﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Web.Security;

public partial class Admin_ConstituentManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "ModalPopup", "function showModal() { $find('ShowModal').show(); }", true);
            BindGridView();
            BindDropDownLists();
            SetNameVisibility(chkIsOrganization.Checked);
        }
    }

    private void BindGridView()
    {
        Common.Utility.BindGridView<Constituent>(grvConstituents, Constituent.GetActivePrimaries());
    }

    private void BindDropDownLists()
    {
        Common.Utility.BindDropDownList<AddressType>(ddlAddressType, AddressType.GetAll(), Common.DefaultValues.AddressType);
        Common.Utility.BindDropDownList<EmailType>(ddlEmailType, EmailType.GetAll(), Common.DefaultValues.EmailType);
        Common.Utility.BindDropDownList<PhoneType>(ddlPhoneType, PhoneType.GetAll(), Common.DefaultValues.PhoneType);
        Common.Utility.BindDropDownList<State>(ddlState, State.GetAll(), Common.DefaultValues.State);  
        Common.Utility.BindDropDownList<Country>(ddlCountry, Country.GetAll(), Common.DefaultValues.CountryAbbreviation, "ABBREVIATION", "ID");     
    }

    protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    {
        Guid id = new Guid(grvConstituents.DataKeys[e.RowIndex].Value.ToString());

        if (Guid.Empty != id)
        {
            Constituent constituent = new Constituent();
            constituent.ID = id;
            constituent.Delete();
        }

        this.BindGridView();
    }

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
            l.Attributes.Add("onclick", "javascript:return confirm('Really delete this constituent?')");
        }
    }

    protected void chkIsOrganization_CheckedChanged(object sender, EventArgs e)
    {
        SetNameVisibility(chkIsOrganization.Checked);        
    }

    private void SetNameVisibility(bool isOrganization)
    {
        pnlConstituent.Visible = !isOrganization;
        pnlOrganization.Visible = isOrganization;
        //rfvName.Enabled = isOrganization;
        //rfvFirstName.Enabled = !isOrganization;
        //rfvLastName.Enabled = !isOrganization;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SaveNewConstituent();
    }

    private void SaveNewConstituent()
    {
        //this happens when they click "save" on the modal form
        //hide the form first so it seems quicker in the front end
        modalNewConstituent.Hide();

        //grab the constituent they entered and create them
        Constituent con = ConstituentFromModalForm();
        con.Create();

        //clear the data they just entered to get ready for next time
        ClearControlsOnContainer(pnlNewGuest);

        //refresh the grid
        BindGridView();
    }

    private List<string> Prefixes()
    {
        List<string> prefixes = new List<string>();
        prefixes.Add("The");

        //return them all as uppercase for comparison
        return prefixes.ConvertAll(x => x.ToUpper());
    }

    /// <summary>
    /// Translates the data entered on the modal form into a constituent object
    /// </summary>
    /// <returns>A fully formed constituent based on data from the modal popup</returns>
    private Constituent ConstituentFromModalForm()
    {
        try
        {
            Constituent constituent = new Constituent();
            string firstname = string.Empty;

            constituent.IsOrganization = chkIsOrganization.Checked;
            constituent.FirstName = (constituent.IsOrganization ? string.Empty : txtFirstName.Text);   //no first name for orgs
            constituent.LastName = (constituent.IsOrganization ? txtOrganizationName.Text : txtLastName.Text);
            constituent.LastNamePrefix = (constituent.IsOrganization ? LastNamePrefixFromLastName(txtOrganizationName.Text) : string.Empty);  //no last name prefix for individuals
            constituent.IsPrimary = true;
            constituent.Address = AddressFromModalPopup();
            constituent.Phone = PhoneFromModalPopup();
            constituent.EmailAddress = EmailFromModalPopup();

            return constituent;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string LastNamePrefixFromLastName(string lastname)
    {
        string firstword = lastname.Split(' ')[0];
        if (Prefixes().Any(str => str.Contains(firstword.ToUpper())))
        {
            return firstword;
        }
        else
        {
            return string.Empty;
        }
    }

    private Address AddressFromModalPopup()
    {
        Address address = new Address();
        address.AddressBlock = txtAddress.Text;
        address.City = txtCity.Text;

        State s = new State();
        s.ID = new Guid(ddlState.SelectedValue);

        address.State = s;

        Country c = new Country();
        c.ID = new Guid(ddlCountry.SelectedValue);

        address.Country = c;
        address.PostCode = txtZip.Text;

        AddressType at = new AddressType();
        at.ID = new Guid(ddlAddressType.SelectedValue);

        address.AddressType = at;

        return address;
    }

    private Email EmailFromModalPopup()
    {
        if (!string.IsNullOrWhiteSpace(txtEmail.Text))
        {
            Email em = new Email();
            em.EmailAddress = txtEmail.Text;

            EmailType et = new EmailType();
            et.ID = new Guid(ddlEmailType.SelectedValue);

            em.EmailAddressType = et;
            return em;
        }
        else
        {
            return null;
        }
    }

    private Phone PhoneFromModalPopup()
    {
        if (!string.IsNullOrWhiteSpace(txtPhone.Text))
        {
            Phone phone = new Phone();
            phone.Number = txtPhone.Text;
            phone.Extension = txtExtension.Text;
            phone.IsPrimary = true;

            PhoneType pt = new PhoneType();
            pt.ID = new Guid(ddlPhoneType.SelectedValue);
            phone.PhoneType = pt;

            return phone;
        }
        else
        {
            return null;
        }
    }

    private void ClearControlsOnContainer(Control container)
    {
        //we hit this code, but the textboxes dont actually get reset.
        //may have to do it from javascript, since the "Save" button never posts back.
        foreach (Control c in container.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Text = string.Empty;
            }
            else if (c is CheckBox)
            {
                ((CheckBox)c).Checked = false;
            }
            else if (c is DropDownList)
            {
                ((DropDownList)c).ClearSelection();
            }
        }
    }

    protected void btnNewConstituent_Click(object sender, EventArgs e)
    {
        pnlNewGuest.Visible = true;
        modalNewConstituent.Show();
    }
}